package com.gewu.pm.ui.activity.clockin;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.other.GridSpaceDecoration;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.adapter.CcPersonAdapter;
import com.gewu.pm.ui.adapter.order.ImageUploadAdapter;
import com.gewu.pm.utils.TextStarUtils;
import com.hjq.bar.TitleBar;
import com.hjq.widget.layout.SettingBar;

import java.util.ArrayList;
import java.util.List;

/**
 * 补卡申请Activity
 */
public final class MakeUpClockInActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    private static final int MAX_PHOTO_COUNT = 5;  // 最多5张图片

    private TitleBar mTitleBar;
    private LinearLayout llClockInTime;
    private TextView tvClockInTimeLabel;
    private TextView tvClockInTimeValue;
    private TextView tvReasonLabel;
    private EditText etReason;
    private RecyclerView rvPhotos;
    private TextView tvApplicantLabel;
    private TextView tvApplicantValue;
    private TextView tvCcLabel;
    private RecyclerView rvCcList;
    private SettingBar btSubmit;

    private ImageUploadAdapter mPhotoAdapter;
    private final List<String> mPhotoList = new ArrayList<>();

    private CcPersonAdapter mCcPersonAdapter;
    private final List<String> mCcPersonList = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent(context, MakeUpClockInActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.make_up_clock_in_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mTitleBar = findViewById(R.id.tb_title);
        llClockInTime = findViewById(R.id.ll_clock_in_time);
        tvClockInTimeLabel = findViewById(R.id.tv_clock_in_time_label);
        tvClockInTimeValue = findViewById(R.id.tv_clock_in_time_value);
        tvReasonLabel = findViewById(R.id.tv_reason_label);
        etReason = findViewById(R.id.et_reason);
        rvPhotos = findViewById(R.id.rv_photos);
        tvApplicantLabel = findViewById(R.id.tv_applicant_label);
        tvApplicantValue = findViewById(R.id.tv_applicant_value);
        tvCcLabel = findViewById(R.id.tv_cc_label);
        rvCcList = findViewById(R.id.rv_cc_list);
        btSubmit = findViewById(R.id.bt_submit);

        // 设置必填项红色星号
        TextStarUtils.setRequiredText(tvClockInTimeLabel,"补卡时间");
        TextStarUtils.setRequiredText(tvReasonLabel,"补卡事由");
        TextStarUtils.setRequiredText(tvApplicantLabel,"申请人");
        TextStarUtils.setRequiredText(tvCcLabel,"抄送人");

        // 初始化上传图片RecyclerView
        rvPhotos.setLayoutManager(new GridLayoutManager(this, 3));
        rvPhotos.addItemDecoration(new GridSpaceDecoration((int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics())));

        // 设置图片适配器
        mPhotoAdapter = new ImageUploadAdapter(this, MAX_PHOTO_COUNT, position -> {
            // 删除图片
            mPhotoList.remove(position);
            updatePhotoList();
        });
        // 设置占位图为 add_ic
        mPhotoAdapter.setPlaceholderResId(R.drawable.add_ic);
        // 启用占位文字显示（如"上传图片(5)"）
        mPhotoAdapter.setShowPlaceholderText(true);
        mPhotoAdapter.setPlaceholderTextPrefix("上传图片");

        // 设置添加图片监听
        mPhotoAdapter.setOnAddListener(() -> {
            // 打开图片选择
            int remainCount = MAX_PHOTO_COUNT - mPhotoList.size();
            if (remainCount > 0) {
                ImageSelectActivity.start(this, remainCount, this);
            } else {
                toast("最多只能上传" + MAX_PHOTO_COUNT + "张图片");
            }
        });

        rvPhotos.setAdapter(mPhotoAdapter);

        // 初始化抄送人RecyclerView
        rvCcList.setLayoutManager(new GridLayoutManager(this, 6));
        mCcPersonAdapter = new CcPersonAdapter(this);
        rvCcList.setAdapter(mCcPersonAdapter);

        // 设置点击事件
        setOnClickListener(llClockInTime, btSubmit);
    }

    @Override
    protected void initData() {
        // 加载模拟数据
        tvApplicantValue.setText("张三");

        // 初始化图片列表（显示占位符）
        updatePhotoList();

        // 模拟抄送人数据
        mCcPersonList.add("张三");
        mCcPersonList.add("李四");
        mCcPersonAdapter.setData(mCcPersonList);
    }

    @SingleClick
    @Override
    public void onClick(android.view.View view) {
        int viewId = view.getId();
        if (viewId == R.id.ll_clock_in_time) {
            // 选择补卡时间
            // TODO: 打开时间选择器
            toast("选择补卡时间");
        } else if (viewId == R.id.bt_submit) {
            // 提交申请
            submitApplication();
        }
    }

    /**
     * 更新图片列表
     */
    private void updatePhotoList() {
        List<String> displayList = new ArrayList<>(mPhotoList);
        
        // 如果未满5张，添加占位符
        if (displayList.size() < MAX_PHOTO_COUNT) {
            displayList.add("camera");
        }

        mPhotoAdapter.setData(displayList);
    }

    /**
     * 提交申请
     */
    private void submitApplication() {
        // 验证补卡时间
        String clockInTime = tvClockInTimeValue.getText().toString().trim();
        if (TextUtils.isEmpty(clockInTime) || clockInTime.equals("2025-01-01 周三 07:00")) {
            toast("请选择补卡时间");
            return;
        }

        // 验证补卡事由
        String reason = etReason.getText().toString().trim();
        if (TextUtils.isEmpty(reason)) {
            toast("请输入补卡事由");
            etReason.requestFocus();
            return;
        }

        // TODO: 提交到服务器
        toast("提交成功");
        finish();
    }

    /**
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> data) {
        if (data != null && !data.isEmpty()) {
            mPhotoList.addAll(data);
            updatePhotoList();
        }
    }
}
